public class WordDistance {
    
    Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
    
    public WordDistance(String[] words) {
        for(int i = 0; i < words.length; i++) {
            List<Ieteger> list = map.get(words[i]);
            if(list == null) {
                list = new ArrayList<Integer>();
            }
            list.add(i);
            map.put(words[i], list);
        }
    }
    
    public int shortest(String word1, String word2) {
        int i = 0, j = 0;
        int distance = Integer.MAX_VALUE;
        List<Integer> idx1 = map.get(word1);
        List<Integer> idx2 = map.get(word2);
        while(i < idx1.size() && j < idx2.size()) {
            distance = Math.min(Math.abs(idx1.get(i)-idx2.get(i)), distance);
            if(idx1.get(i) < idx2.get(j))
                i++;
            else
                j++;
        }
        return distance;
    }
    
}